package operations

import (
	"github.com/sirupsen/logrus"
	"mydocker/common"
	"mydocker/container"
	"mydocker/network"
)

// RemoveContainer 删除容器
func RemoveContainer(containerID string, force bool) {
	info, err := getInfoByContainerID(containerID)
	if err != nil {
		logrus.Errorf("Get container %s info error %v", containerID, err)
		return
	}
	switch info.Status {
	case common.Stop: // Stop 状态容器直接删除即可
		// 先删除配置目录，再删除 rootfs 目录
		if err = container.DeleteContainerInfo(containerID); err != nil {
			logrus.Errorf("Remove container [%s]'s config failed, detail: %v", containerID, err)
			return
		}
		container.DeleteWorkSpace(containerID, info.Volume)
		if info.NetworkName != "" { // 清理网络资源
			if err = network.Disconnect(info.NetworkName, info); err != nil {
				logrus.Errorf("Remove container [%s]'s network failed, detail: %v", containerID, err)
				return
			}
		}
	case common.Running: // Running 状态容器如果指定了 force 则先 stop 然后再删除
		if !force {
			logrus.Errorf("Couldn't remove running container [%s], Stop the container before attempting removal or force remove", containerID)
			return
		}
		logrus.Infof("Force delete running container [%s]", containerID)
		StopContainer(containerID)
		RemoveContainer(containerID, force)
	default:
		logrus.Errorf("Couldn't remove container,invalid status %s", info.Status)
		return
	}
}
